<template>
  <div class="home-page container-md">
    <section class="text-center container">
      <div class="row py-lg-5">
        <div class="col-lg-6 col-md-8 mx-auto">
          <img src="../assets/callout.svg" alt="callout" class="w-50" />
          <h2 class="font-weight-light">随心写作，自由表达</h2>
          <router-link :to="redirectTo" class="btn btn-primary my-2">
            开始写文章
          </router-link>
        </div>
      </div>
    </section>
    <h4 class="font-weight-bold text-center mb-4">发现精彩</h4>
    <column-list :list="list"></column-list>
    <button v-if="!isShow" :class="loadMoreClass" @click="loadMore()">
      加载更多
    </button>
  </div>
</template>

<script lang='ts'>
import { defineComponent, computed, onMounted, ref } from 'vue'
import { useStore } from 'vuex'
import { GlobalDataProps } from '@/store'
import ColumnList from '../components/ColumnList.vue'

const loadMoreClass = [
  'btn',
  'btn-outline-primary',
  'mt-2',
  'mb-5',
  'mx-auto',
  'd-block',
  'w-25'
]

export default defineComponent({
  components: {
    ColumnList
  },
  setup () {
    const store = useStore<GlobalDataProps>()

    const currentPage = ref(1)
    const totalCount = ref(0)

    const loadMore = () => {
      store.dispatch('fetchColumns', currentPage.value).then((res) => {
        currentPage.value++
        totalCount.value = res.data.count
      })
    }

    const isShow = computed(() => {
      return Math.ceil(totalCount.value / 6) === currentPage.value - 1
    })

    const list = computed(() => {
      return store.getters.getColumns
    })

    onMounted(() => {
      store.commit('clearColumns')
      store.dispatch('fetchColumns', currentPage.value).then((res) => {
        currentPage.value++
        totalCount.value = res.data.count
      })
    })

    const redirectTo = computed(() => {
      return store.state.user.isLogin ? '/create' : '/register'
    })

    return {
      list,
      loadMore,
      loadMoreClass,
      isShow,
      redirectTo
    }
  }
})
</script>

<style scoped>
.font-weight-light {
  font-weight: 300;
}

.font-weight-bold {
  font-weight: 700;
}
</style>
